#include "myfile.h"


_FILE* _fopen(const char* name, const char* mode)
{
    int flag = 0;
    if(strcmp(mode, "w") == 0) flag = O_CREAT|O_WRONLY|O_TRUNC;
    if(strcmp(mode, "r") == 0) flag = O_RDONLY;
    if(strcmp(mode, "a") == 0) flag = O_CREAT|O_WRONLY|O_APPEND;

    int fd = open(name, flag, MODE);
    _FILE* file = (_FILE*)malloc(sizeof(_FILE));
    file->_fileno = fd;
    return file;
}

int _fwrite(const char* s,size_t size,size_t count,_FILE* name)
{
    //模拟行刷新
    if(name->pos + size*count >= SIZE)
        return 0;
    memcpy(name->buffer + name->pos, s, size * count);
    name->pos += size * count;
    if(name->buffer[name->pos-1] == '\n')
    {
        //刷新缓冲区
        ssize_t ret = write(name->_fileno, name->buffer, name->pos);
        if(ret < 0)
        {
            return 0;
        }
    }
}

int _fclose(_FILE* name)
{
    return close(name->_fileno);
}
